import TagGroup from '@/components/TagGroup';
import UploadDragger from '@/pages/cues/components/UploadDragger';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import { getCuesSubmitDetails, saveCuesSubmit } from '@/services/api/api-cues-submit';
import { CheckCircleTwoTone, FileSearchOutlined, SendOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProCard,
  ProForm,
  ProFormDatePicker,
  ProFormInstance,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea
} from '@ant-design/pro-components';

import { ActionType } from '@ant-design/pro-table';
import { Button, Col, message, Row, Spin } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddSubmitPreview from './AddSubmitPreview';

interface EditSubmitProps {
  id: string;
  onRefurbish: () => void;
}

const EditSubmit: React.FC<EditSubmitProps> = ({ onRefurbish, id }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [industrys, setIndustrysState] = useState<any[]>([]);

  const [openAddSubmit, setOpenAddSubmit] = useState<boolean>(false);

  const [openAddSubmitPreview, setOpenAddSubmitPreview] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState<CuesSubmitBo.AddSubmitPreview>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const [initialValuesData, setInitialValuesDataState] = useState<CuesSubmitData.SubmitDetails>();

  const [green, setGreen] = useState<boolean>(false);

  /**
   * 获取 详情
   * @param key
   */
  const getSubmitDetails = async () => {
    try {
      const response = await getCuesSubmitDetails({ id });
      if (response.code === 0) {
        console.log(response.data?.articleLabels);
        formRef.current?.setFieldsValue({
          articleName: response.data?.articleName,
          articleIndustryIds: response.data?.articleIndustrys,
          articleLabels: response.data?.articleLabels.map((item) => item.label),
          articleContent: response.data?.articleContent,
          remarks: response.data?.remarks,
          articleAttachments: response.data?.articleAttachments,
        });
        setInitialValuesDataState(response.data);
      }
    } catch (error) {}
  };
  // /**
  //  * 加载权限详情
  //  * @param key
  //  */
  // const getCuesIndustryData = async () => {
  //     try {
  //         const response = await listCuesIndustry();

  //         setIndustrysState(
  //             response.data.map((item) => {
  //                 return { label: item.name, value: item.id };
  //             }),
  //         );
  //     } catch (error) { }
  // };

  return (
    <DrawerForm
      key="drawer_form_add_submit"
      title="编辑线索"
      drawerProps={{
        maskClosable: false,
        // destroyOnClose: true,
        width: 1150,
      }}
      formRef={formRef}
      trigger={<a>编辑</a>}
      open={openAddSubmit}
      onOpenChange={(visible) => {
        getSubmitDetails();
        setOpenAddSubmit(visible);
        console.log(initialValuesData);
        if (visible) {
          console.log(initialValuesData);
          // getCuesIndustryData();
        }
      }}
      layout="horizontal"
      submitter={{
        searchConfig: {
          submitText: (
            <>
              <FileSearchOutlined /> 预览
            </>
          ),
        },
        render: (props, defaultDoms) => {
          return [
            defaultDoms,
            <Button
              key="button_add_submit"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                /**
                 * ======================
                 * 直接发布
                 * ======================
                 */
                const values = formRef.current?.getFieldsValue();

                if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                  message.warning('请输入标题');
                  return;
                }

                if (
                  !(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)
                ) {
                  message.warning('请选择至少一个选题方向');
                  return;
                }

                if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                  message.warning('请输入至少一个标签');
                  return;
                }

                if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                  message.warning('请输入线索内容');
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <AddSubmitPreview
              key="add_submit_preview"
              onSubmit={() => {
                setOpenAddSubmit(false);
                onRefurbish();
              }}
              open={openAddSubmitPreview}
              onOpenChange={(open) => {
                setOpenAddSubmitPreview(open);
              }}
              details={previewData}
            />,
            <ModalForm
              key={'modal_form_add_submit'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                const values = formRef.current?.getFieldsValue();

                if (
                  values.articleAttachments !== undefined &&
                  values.articleAttachments.length > 0
                ) {
                  const articleAttachments = values.articleAttachments.map(
                    (item: { response: { data: { id: any } } }) => {
                      return item.response.data.id;
                    },
                  );

                  values.articleAttachments = articleAttachments;
                }

                const response = await saveCuesSubmit({
                  id: id,
                  topicId: initialValuesData?.topicId,
                  articleName: values?.articleName,
                  articleIndustryIds: values?.articleIndustryIds,
                  articleLabels: values?.articleLabels,
                  remarks: values?.remarks,
                  articleContent: values?.articleContent,
                  articleAttachments: values?.articleAttachments,
                  createdSource: 1,
                });

                if (response.code === 0) {
                  message.success('提交成功');
                  setOpenAddSubmit(false);
                  onRefurbish();
                  return true;
                } else {
                  return false;
                }
              }}
            />,
          ];
        },
      }}
      onFinish={async (values) => {
        /**
         * ======================
         * 预览发布
         * ======================
         */
        if (!(values.articleName !== undefined && values.articleName.length > 0)) {
          message.warning('请输入标题');
          return;
        }

        if (!(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)) {
          message.warning('请选择至少一个选题方向');
          return;
        }

        if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
          message.warning('请输入至少一个标签');
          return;
        }

        if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
          message.warning('请输入线索内容');
          return;
        }

        console.log(values.articleIndustryIds);

        // const articleIndustrys = values.articleIndustryIds?.map((item) => {
        //     const industry = industrys.find((e) => e.value === item);
        //     return industry;
        // });

        if (values.articleSetDate) {
          values.articleSetDate = dayjs(values.articleSetDate).format('YYYY-MM-DD');
        }

        setPreviewData({
          id: id,
          topicId: initialValuesData?.topicId,
          topicName: initialValuesData?.topicName,
          articleName: values.articleName,
          articleIndustrys: values.articleIndustryIds,
          articleLabels: values.articleLabels,
          articleSetDate: values?.articleSetDate,
          articleLocation: values?.articleLocation,
          articleHighlight: values?.articleHighlight,
          contacts: values?.contacts,
          articleContent: values.articleContent,
          createdSource: 1,
          articleAttachments: values.articleAttachments,
        });

        setOpenAddSubmitPreview(true);
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={initialValuesData === undefined}
      >
        <ProFormText
          width="xl"
          name="articleName"
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标题
            </>
          }
          fieldProps={{
            allowClear: true,
            maxLength: 200,
          }}
        />
        <ProFormSelect
          width="xl"
          name="articleIndustryIds"
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              选题方向
            </>
          }
          // options={industrys}
          request={async () => {
            const response = await listCuesIndustry();
            return response.data.map((item) => {
              return { label: item.name, value: item.id };
            });
          }}
          fieldProps={{
            mode: 'multiple',
            labelInValue: true,
            allowClear: true,
          }}
        />
        <ProForm.Item
          label={
            <>
              <span
                style={{
                  color: '#ff4d4f',
                  fontSize: 14,
                  paddingRight: 4,
                }}
              >
                *
              </span>
              标签
            </>
          }
          name="articleLabels"
          extra={'最少输入一个'}
        >
          <TagGroup
            style={{
              marginLeft: '28px',
            }}
          />
        </ProForm.Item>
        <ProFormDatePicker
          name="articleSetDate"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              线索日期
            </span>
          }
          width="xl"
          fieldProps={{
            allowClear: true,
            maxLength: 200,
            format: 'YYYY-MM-DD',
          }}
        />
        <ProFormTextArea
          name="articleLocation"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              地点
            </span>
          }
          width="xl"
          fieldProps={{
            allowClear: true,
            rows: 3,
            maxLength: 100,
            showCount: true,
            style: {
              marginLeft: '28px',
            },
          }}
        />

        <ProFormTextArea
          name="articleHighlight"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              亮点
            </span>
          }
          width="xl"
          fieldProps={{
            allowClear: true,
            rows: 3,
            maxLength: 100,
            showCount: true,
            style: {
              marginLeft: '28px',
            },
          }}
        />

        <ProFormList
          name="contacts"
          label="联络方式"
          creatorButtonProps={{
            creatorButtonText: '添加联络人',
          }}
          required={true}
          itemRender={({ listDom, action }, { index }) => {
            return (
              <ProCard
                bordered
                title={false}
                style={{
                  marginBlockEnd: 8,
                }}
                bodyStyle={{
                  paddingBottom: 0,
                }}
              >
                <Row>
                  <Col span={23}>{listDom}</Col>
                  <Col span={1}>{action}</Col>
                </Row>
              </ProCard>
            );
          }}
          copyIconProps={false}
        >
          <ProFormText
            width="md"
            name="name"
            label="联络人"
            required={true}
            fieldProps={{
              allowClear: true,
              maxLength: 200,
            }}
          />
          <ProFormText
            width="md"
            name="phone"
            label="联系电话"
            required={true}
            fieldProps={{
              allowClear: true,
              maxLength: 200,
            }}
            rules={[
              {
                pattern:
                  /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                message: '请输入正确的手机号',
              },
            ]}
          />
        </ProFormList>

        <ProCard ghost>
          <ProCard colSpan={green ? '750px' : '1'} ghost>
            <ProFormTextArea
              name="articleContent"
              label={
                <span>
                  <span
                    style={{
                      color: '#ff4d4f',
                      fontSize: 14,
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  线索内容
                </span>
              }
              width="xl"
              fieldProps={{
                allowClear: true,
                rows: 5,
                maxLength: 200,
                showCount: true,
              }}
            />
          </ProCard>
        </ProCard>
        <FormItem
          name="articleAttachments"
          hidden={!access.线索征集x报送线索x附件}
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              附件
            </span>
          }
        >
          <UploadDragger
            onPreview={(file) => {}}
            access={{
              isPicture: access.线索征集x报送线索x附件x图片,
              isVideo: access.线索征集x报送线索x附件x视频,
              isOffice: access.线索征集x报送线索x附件x办公,
              isOther: access.线索征集x报送线索x附件x其他,
            }}
            url="/cues/attachment/save"
            mode="submit"
          />
        </FormItem>
      </Spin>
    </DrawerForm>
  );
};
export default EditSubmit;
